<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\UserInfo;
use App\Models\UserViolate;
use App\Validate\UserInfoValidate;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 用户管理模块
 */
class UserInfoController extends CommonController
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new UserInfo();
        $this->validate = new UserInfoValidate();
    }

    /**
     * 用户列表
     * @param page 默认为 1
     * @param limit 限制条数 默认为 10
     * @param keywords 检索内容
     * @param keywords_type 关键词类型  1 读者证号 2 读者证号名字 3身份证号码 4电话号码 5微信昵称
     * @param is_volunteer 是否是志愿者 0全部  1 是  2 否
     * @param is_violate 是否违规 0全部  1 是  2 否
     * @param sort 排序方式   1 默认排序（默认）  2 积分倒序  3 邀请数量排序
     */
    public function lists()
    {
        //异步发送数据
        if (!Cache::get('user_info_async_send')) {
            Cache::put('user_info_async_send', 1, 3 * 60);//防止重复执行
            $url = $this->getHostUrl() . '/admin/userInfo/asyncSend';
            request_url($url, null, 1);
        }

        $page = intval($this->request->page) ?: 1;
        $limit = $this->request->limit ?: 10;
        $keywords = $this->request->keywords;
        $keywords_type = $this->request->keywords_type;
        $is_volunteer = $this->request->is_volunteer;
        $is_violate = $this->request->is_violate;
        $sort = $this->request->input('sort', 1);
        //  $sort = $sort == 2 ? 'score' : 'create_time';

        $res = $this->model->lists($keywords, $keywords_type, $is_volunteer, $is_violate, $sort, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "暂无数据");
        }

        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 异步请求数据
     */
    public function asyncSend()
    {
        $userViolateModel = new UserViolate();
        $violate_config = config("other.violate_config");
        if ($violate_config) {
            $violate_config_field = array_column($violate_config, 'field');
            $userViolateModel->resetViolate('', $violate_config_field); //重置一次查询数据
        }
    }

    /**
     * 清空违规次数
     * @param user_id 用户id 
     * @param node  all 全部清空  其余，根据违规返回字段清空  多个逗号拼接
     */
    public function clearViolate()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('clear_violate')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $violate_config = config("other.violate_config");
        $violate_config_field = array_column($violate_config, 'field');
        if (empty($violate_config)) {
            return $this->returnApi(202, "需要清空的数据不存在");
        }

        $node = $this->request->node;
        if ($node !== 'all') {
            $node_arr = explode(',', $node);
            foreach ($node_arr as $key => $val) {
                if (!in_array($val, $violate_config_field)) {
                    return $this->returnApi(202, "需要清空的数据不存在");
                }
            }
            $violate_config_field = $node_arr; //只修改这些
        }

        DB::beginTransaction();
        try {
            $userViolateModel = new UserViolate();
            $userViolateModel->clearViolate($this->request->user_id, $violate_config_field);

            Cache::forget('violate_number'); //重置违规数量

            DB::commit();
            return $this->returnApi(200, "清空成功");
        } catch (\Exception $e) {
            DB::rollBack();
            // return $this->returnApi(202, $e->getMessage().$e->getFile().$e->getLine());
            return $this->returnApi(202, '清空失败');
        }
    }

    /**
     * 获取用户违规列表
     * @param user_id 用户id 
     * @param node  根据违规返回字段  activity  活动违规（手动违规） reservation 预约违规（手动+自动）contest 大赛违规（手动违规） 
     *                               scenic 景点打卡（手动违规） study_room_reservation 空间预约违规（手动+自动） 对应字段值
     * @param page 默认为 1
     * @param limit 限制条数 默认为 10
     */
    public function getViolateList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('violate_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_id;
        $node = $this->request->node;
        $page = intval($this->request->page) ?: 1;
        $limit = $this->request->limit ?: 10;

        $userViolateModel = new UserViolate();
        $res = $userViolateModel->getUserViolateList($user_id, $node, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

        return $this->returnApi(200, "查询成功", true, $res);
    }
}
